package com.zx.zxapibackend.security.exception;

import com.alibaba.fastjson.JSON;
import com.zx.zxapicommon.common.BaseResponse;
import com.zx.zxapicommon.model.enums.ErrorCode;
import com.zx.zxapicommon.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张旭
 * @version 1.0
 * 自定义认证异常处理类：对应401
 */
@Component
@Slf4j
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        BaseResponse error = ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "认证失败，请重新登录11");
        log.error("用户名或者密码错误，请再次尝试。。。。。。。。");
        String json = JSON.toJSONString(error);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json);
    }
}
